<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/19 0019
 * Time: 9:42
 * op: 铭感词服务
 */
namespace App\Service;

class BlackWord
{
    private $outpath = ''; //字典存放输出路径

    public function __construct($outpath = '')
    {
        if($outpath) {
            $this->outpath = $outpath;
        }else{
            $this->outpath = base_path().'/storage/blackword.tree';
        }
    }

    /**
     * 生成字典
     * @param $inpath 字典路径
     * @param $outpath 输出字典路径
     */
    public function createDict($inpath)
    {
        // 设置内存
        ini_set('memory_limit', '128M');
        // 读取敏感词字典库
        $handle = fopen($inpath, 'r');
        // 生成空的trie-tree-filter
        $resTrie = trie_filter_new();
        while(! feof($handle)) {
            $item = trim(fgets($handle));
            if (empty($item)) {
                continue;
            }
            // 把敏感词逐个加入trie-tree
            trie_filter_store($resTrie, $item);
        }
        fclose($handle);
        // 生成trie-tree文件
        $blackword_tree = $this->outpath;
        $res = trie_filter_save($resTrie, $blackword_tree);

        return $res ? true : false;
    }

    /**
     * 敏感词查询替换
     * @param $str
     */
    public function searchReplace($str)
    {
        if(empty($str)) {
            return false;
        }

        $resTrie = trie_filter_load($this->outpath);
        $strContent = $str;
        while(1) {
            $arrRet = trie_filter_search($resTrie, $strContent);
            if(empty($arrRet)) {
                break;
            }
            $strContent = substr_replace($strContent,'*', $arrRet[0], $arrRet[1]);
        }

        return $strContent;
    }

    //获取输出路径
    public function getPath()
    {
        return $this->outpath;
    }

}

